const Service = require('egg').Service;

class WeixinService extends Service {

	async getSignature (wxid, url) {

        const { service, app } = this;

        const noncestr = await service.util.uuid(16, 62);//Wm3WZYTPz0wzccnW

        //app.logger.info(noncestr);

        let newwxid = wxid;
        if(wxid == '4') newwxid = '2';  //测试的。

        const jsapi_ticket = await app.redis.get('system').hget('dlq_token', newwxid);//sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg

        const obj = JSON.parse(jsapi_ticket);

        let timestamp = (new Date()).getTime() + '';

        let t = timestamp.substring(0, timestamp.length - 3); 

        const arr = url.split('https://');

        const str = 'jsapi_ticket=' + obj.jsapi_ticket +
        '&noncestr=' + noncestr + 
        '&timestamp=' + t + 
        '&url=' + url;

        //app.logger.info(str);

        const signature = app.sha1(str);

        //app.logger.info(signature);

        return {
            noncestr,
            'timestamp' : t,
            signature,
        }

    }

    //直接向商家支付。
    async createOrder2Merchant (code, pay_wxid, title, total_fee, product_id) {

        const { service, app, ctx } = this;

        //const companyInfo = await service.company.info(company_code);

        const wxinfo = await service.company.infoByWXid(pay_wxid);

        const noncestr = await service.util.uuid(16, 62);

        const ip = ctx.request.header['x-real-ip'];

        const p = {
            appid : wxinfo.appid,
            mch_id : wxinfo.mch_id,
            nonce_str : noncestr,
            body : title,
            attach : wxinfo.wxid,
            out_trade_no : code,
            total_fee : total_fee,
            spbill_create_ip : ip,
            notify_url : 'https://api.hidlq.com/wxpaycallback',
            trade_type : 'NATIVE',
            product_id,
        };

        let stringA = '';
        Object.keys(p).sort().forEach(k => {
            stringA += k + '=' + p[k] + '&';
        });
        stringA += "key=" + wxinfo.md5_key;

        console.log(stringA);
        //app.logger.info('stringA : ' + stringA);

        const sign = app.md5(stringA).toUpperCase();
        //app.logger.info('sign : ' + sign);

        p['sign'] = sign;

        const xml = app.x2js.js2xml({
            'xml' : p
        });

        //app.logger.info('xml : ' + xml);

        return xml;

    }


    //用户下单
    async createOrder (code, company_code, openid, title, total_fee) {

        const { service, app, ctx } = this;

        const companyInfo = await service.company.info(company_code);

        const wxinfo = await service.company.infoByWXid(companyInfo.pay_wxid);

        const md5_key = wxinfo.md5_key;

        const noncestr = await service.util.uuid(16, 62);

        const ip = ctx.request.header['x-real-ip'];

        const now = new Date();

        const haha = new Date(now.getTime() +  1000 * 60 * 8 );

        const now1 = ctx.helper.dateFtt("yyyyMMddhhmmss",now);
        const haha1 = ctx.helper.dateFtt("yyyyMMddhhmmss",haha);

        const p = {
            appid : wxinfo.appid,
            mch_id : wxinfo.mch_id,
            nonce_str : noncestr,
            body : title,
            attach : wxinfo.wxid,
            out_trade_no : code,
            total_fee : total_fee,
            spbill_create_ip : ip,
            time_start : now1,
            time_expire : haha1,
            notify_url : 'https://api.hidlq.com/wxpaycallback',
            trade_type : 'JSAPI',
            openid,
        };

        let stringA = '';
        Object.keys(p).sort().forEach(k => {
            stringA += k + '=' + p[k] + '&';
        });
        stringA += "key=" + wxinfo.md5_key;

        console.log(stringA);
        //app.logger.info('stringA : ' + stringA);

        const sign = app.md5(stringA).toUpperCase();
        //app.logger.info('sign : ' + sign);

        p['sign'] = sign;

        const xml = app.x2js.js2xml({
            'xml' : p
        });

        //app.logger.info('xml : ' + xml);

        return xml;
    }


    async getPaySignature (wxid, appid, prepay_id, md5_key) {

        const { service, app } = this;

        let timestamp = (new Date()).getTime() + '';
        let t = timestamp.substring(0, timestamp.length - 3); 

        const noncestr = await service.util.uuid(16, 62);

        const signtype = 'MD5';

        const jsapi_ticket = await app.redis.get('system').hget('dlq_token', wxid);//sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg

        const obj = JSON.parse(jsapi_ticket);

        let str = 'appId=' + appid +
        '&nonceStr=' + noncestr + 
        '&package=prepay_id=' + prepay_id +
        '&signType=' + signtype +
        '&timeStamp=' + t +
        '&key=' + md5_key;

        //app.logger.info(str);

        let sign = app.md5(str).toUpperCase();

        //app.logger.info(sign);

        return {
            'timestamp' : t,
            'noncestr' : noncestr,
            'package' : 'prepay_id=' + prepay_id,
            'signtype' : signtype,
            'paysign' : sign,
        }

    }



    async checkSign (para, md5_key) {
        console.log('checkSign');

        let stringA = '';

        Object.keys(para).sort().forEach(k => {
            if(k != 'sign'){
                stringA += k + '=' + para[k] + '&';
            }
        });

        stringA += "key=" + md5_key;

        //this.ctx.logger.info(stringA);

        const sign = this.app.md5(stringA).toUpperCase();

        // this.ctx.logger.info(sign);
        // this.ctx.logger.info(para.sign);

        return para.sign == sign;

    }



    //退款
    async refund(para){

        const { service, app } = this;

        const {wxid, transaction_id, out_refund_no, total_fee, refund_fee} = para;

        const wxinfo = await service.company.infoByWXid(wxid);

        const noncestr = await service.util.uuid(16, 62);

        const p = {
            appid : wxinfo.appid,
            mch_id : wxinfo.mch_id,
            nonce_str : noncestr,
            transaction_id,
            out_refund_no,
            total_fee,
            refund_fee,
            notify_url : 'https://api.hidlq.com/wxrefundcallback',
        };

        let stringA = '';
        Object.keys(p).sort().forEach(k => {
            stringA += k + '=' + p[k] + '&';
        });
        stringA += "key=" + wxinfo.md5_key;

        //this.ctx.logger.info(stringA);

        const sign = this.app.md5(stringA).toUpperCase();

        const xml = app.x2js.js2xml({
            'xml' : {
                ...p,
                sign
            }
        });

        //app.logger.info('xml : ' + xml);

        return xml;
    }

  	
}

module.exports = WeixinService;